package com.reguang.system.shiro;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import com.reguang.common.utils.ShiroUtils;
import com.reguang.pojo.SysUserDO;
import com.reguang.service.SysMenuService;
import com.reguang.service.SysUserService;
import com.reguang.utils.ObjectUtils;

public class UserRealm extends AuthorizingRealm {

	@Autowired
	SysUserService sysUserService;

	@Autowired
	SysMenuService sysMenuService;

	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection arg0) {
		String userId = ShiroUtils.getUserId();
		Set<String> perms = sysMenuService.listPerms(userId);
		SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
		info.setStringPermissions(perms);
		return info;
	}

	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
		String nickname = (String) token.getPrincipal();
		Map<String, Object> map = new HashMap<>(16);
		map.put("nickname", nickname);
		String password = new String((char[]) token.getCredentials());

		SysUserDO record = new SysUserDO();
		record.setNickName(nickname);
		record.setPassword(password);
		// 查询用户信息
		SysUserDO sysUserDO = sysUserService.queryOne(record);

		// 账号不存在
		if (ObjectUtils.isNull(sysUserDO)) {
			throw new UnknownAccountException("账号或密码不正确");
		}

		// 密码错误
		if (!password.equals(sysUserDO.getPassword())) {
			throw new IncorrectCredentialsException("账号或密码不正确");
		}

		// 账号锁定
		if (sysUserDO.getStatus() == 0) {
			throw new LockedAccountException("账号已被锁定,请联系管理员");
		}
		SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(sysUserDO, password, getName());
		return info;
	}

}
